package com.cy.myblog.action.login;

import com.alibaba.fastjson.JSON;
import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.TloginAddr;
import com.cy.myblog.model.TloginInfo;
import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.Json;
import com.cy.myblog.pageModel.User;
import com.cy.myblog.service.LoginAddrServiceI;
import com.cy.myblog.service.LoginInfoServiceI;
import com.cy.myblog.service.UserServiceI;
import com.cy.myblog.util.Encrypt;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Controller
@Scope("prototype")
@ParentPackage("basePackage")
@Namespace("/login")
@Action(value = "loginAction")
@Results({@Result(name = "success", type="json", params={"root","jsonMsg"})})
public class LoginAction extends BaseAction implements ModelDriven<User>{

	private UserServiceI userService;
	private LoginInfoServiceI loginInfoService;
	private LoginAddrServiceI loginAddrService;

	private String jsonMsg;

	private User user = new User();
	private String remenber = "no";
	private String uuid;
	private String code;

	@Autowired
	public void setLoginInfoService(LoginInfoServiceI loginInfoService) {
		this.loginInfoService = loginInfoService;
	}

	@Autowired
	public void setUserService(UserServiceI userService) {
		this.userService = userService;
	}

	@Autowired
	public void setLoginAddrService(LoginAddrServiceI loginAddrService) {this.loginAddrService = loginAddrService;}

	public void ipAddress(){
//		String agent = ServletActionContext.getRequest().getHeader("user-agent");
//		System.out.println(agent);
//        //操作系统信息
//		System.out.println(System.getProperty("os.name"));
//		System.out.println(System.getProperty("os.version"));
//		System.out.println(System.getProperty("os.arch"));

		String ip = super.getIpAddr();
		Json json = new Json();
		int times = 0;
		TloginAddr loginAddress = loginAddrService.getByAddress(ip);
		if(loginAddress == null){
			loginAddress = new TloginAddr();
			loginAddress.setAddress(ip);
			loginAddress.setTimes(times);
			loginAddrService.save(loginAddress);
		}else{
			times = loginAddress.getTimes();
		}

		if(times < 5){
			json.setShowCode(false);
		}else{
			json.setShowCode(true);
		}
		writeJson(json);
	}

	//太过于复杂,有空再优化
	public String login(){
		Json json = new Json();
		String ip = super.getIpAddr();
		TloginInfo info = loginInfoService.getById(uuid);
		TloginAddr loginAddress = loginAddrService.getByAddress(ip);
		int times = 1;

		if(loginAddress == null){
			loginAddress = new TloginAddr();
			loginAddress.setAddress(ip);
			loginAddress.setTimes(times);
			loginAddrService.save(loginAddress);
		}else{
			times = loginAddress.getTimes();
		}

		if(times >= 5){
			json.setShowCode(true);
			if(info != null){
				if(!code.equalsIgnoreCase(info.getCode())) {
					json.setMsg("验证码输入错误!");
					json.setSuccess(false);
					jsonMsg = JSON.toJSONString(json);
					return "success";
				}
			} else {
				json.setMsg("系统繁忙!");
				json.setSuccess(false);
				jsonMsg = JSON.toJSONString(json);
				return "success";
			}
		}else{
			loginAddress.setTimes(++times);
			loginAddrService.update(loginAddress);
			if(times >=5){
				json.setShowCode(true);
			}
		}

		if(StringUtils.isBlank(user.getAccount()) || StringUtils.isBlank(user.getPassword())){
			json.setMsg("登录失败,用户名或密码不能为空!");
			json.setSuccess(false);
			jsonMsg = JSON.toJSONString(json);
			return "success";
		}

		user.setPassword(Encrypt.md5(user.getPassword()));
		Tuser tu = userService.getByHql(user);

		if(tu == null){
			json.setMsg("登录失败,用户名或密码错误!");
			json.setSuccess(false);
			jsonMsg = JSON.toJSONString(json);
			return "success";
		}

		session.put("loginUser", tu);
		loginAddress.setTimes(0);
		loginAddrService.update(loginAddress);

		/*
		*  bug: 此处cookie保存无效,初步判断为ajax通信没有把response里的cookie发回客户端,
		*       需要使用转发来完成,但是这样需要重写整个登录功能,所以暂时先放一边.(已解决)
        */
		// 解决方法: 此处使用客户端js来保存cookie,解决上述问题.
		if(remenber.equals("yes")){
			HttpServletResponse res = ServletActionContext.getResponse();
			//需要注意这里cookie的内容不能使用一些符号,如:':',思考解决方法为使用encodeURI()和decodeURI()进行编码解码.此方法没有实验过.
			String value = "account_" + user.getAccount() + "pwd_" + user.getPassword() +".";
			String name = "cookieuser";
			int maxAge = 7;
			json.setCokiName(name);
			json.setCokvalue(value);
			json.setCokrem(remenber);
			json.setCokMaxAge(maxAge);
		}

		tu.setLogintime(new Date());
		tu.setIpaddress(super.getIpAddr());
		userService.update(tu);

		json.setCurAcount(tu.getAccount());
		json.setMsg("登录成功!");
		json.setSuccess(true);
		jsonMsg = JSON.toJSONString(json);
		return "success";
	}

	@Override
	public User getModel() {
		return user;
	}

	public String getRemenber() {
		return remenber;
	}

	public void setRemenber(String remenber) {
		this.remenber = remenber;
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getJsonMsg() {
		return jsonMsg;
	}

	public void setJsonMsg(String jsonMsg) {
		this.jsonMsg = jsonMsg;
	}

}
